﻿@*
//------------------------------------------------------------------------------
//  此代码版权声明为全文件覆盖，如有原作者特别声明，会在下方手动补充
//  此代码版权（除特别声明外的代码）归作者本人Diego所有
//  源代码使用协议遵循本仓库的开源协议及附加协议
//  Gitee源代码仓库：https://gitee.com/diego2098/ThingsGateway
//  Github源代码仓库：https://github.com/kimdiego2098/ThingsGateway
//  使用文档：https://diego2098.gitee.io/thingsgateway-docs/
//  QQ群：605534569
//------------------------------------------------------------------------------
*@

@page "/gatewayruntime/devicestatus"
@namespace ThingsGateway.Gateway.Blazor
@using System.Linq.Expressions;
@using BlazorComponent;
@using Mapster;
@using Masa.Blazor
@using Masa.Blazor.Presets;
@using System.IO;
@using Microsoft.AspNetCore.Authorization;
@using SqlSugar;
@using ThingsGateway.Admin.Blazor;
@using ThingsGateway.Admin.Core;

@attribute [Authorize]
@inherits BaseComponentBase
@inject UserResoures UserResoures
@inject NavigationManager NavigationManager

@layout MainLayout
<MSheet Style="overflow:auto">


    <MTabs @bind-Value="_tabNumber">
        <MTab Value="1">
            采集设备状态
        </MTab>
        <MTab Value="2">
            上传设备状态
        </MTab>
        <MButton Class="position-button" Disabled=@(!UserResoures.IsHasButtonWithRole("gatewaydevicerestart")) Color="red" Dark Fab XSmall Loading=_isAllRestart OnClick="AllRestartAsync">
             <MIcon>   mdi-restart   </MIcon>
         </MButton>
     </MTabs>
     <MTabsItems Value="_tabNumber">
         <MTabItem Value="1">
             @if (_tabNumber == 1)
            {
                <MRow NoGutters>
@*                  <MCol Md=2 Cols="12">

                     <MCard Class="ma-2" Style=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight + 80}px );")>
                         <MCardTitle>
                             <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="mx-2 my-1" @bind-Value="_collectDeviceSearchName"
                                            Outlined Label=@typeof(CollectDevice).GetDescription(nameof(CollectDevice.DeviceGroup)) />
                             </MCardTitle>

                             <MTreeview Style=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight + 240}px; overflow-y:auto)") Dense TItem="string" TKey="string" ActiveChanged=@(async a=>
                                   {
                                   if(_collectDeviceGroup!=a.FirstOrDefault())
                                   {
                                   _collectDeviceGroup=a.FirstOrDefault(); CollectDeviceQuery();
                                   }
                                   } )
                                        Items="_collectDeviceGroups" ItemText="r=>r" ItemChildren="r=>null"
                                        Search="@_collectDeviceSearchName"
                                      Activatable ItemKey=@(r=>r)>
                                 <LabelContent>
                                     <span title=@context.Item>
                                         @context.Item
                                    </span>
                                </LabelContent>
                            </MTreeview>
                        </MCard>
                    </MCol> *@
                    <MCol Md=5 Cols="12">
                        <MCard Height=@($"calc(100vh - {BlazorResourceConst.DefaultHeight + 80}px; )") Style="overflow-y:auto;" Flat Class="ml-2 my-4">

                              <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="mx-2 my-1" @bind-Value="_collectDeviceSearchName"
                                            Outlined Label=@typeof(CollectDevice).GetDescription(nameof(CollectDevice.Name)) />

                             <MVirtualScroll Context="item" Height=@($"calc(100vh - {BlazorResourceConst.DefaultHeight+140}px)") OverscanCount=2 ItemSize="60" Items="_collectDriverBases.WhereIF(!_collectDeviceSearchName.IsNullOrEmpty(),a=>a.CurrentDevice.Name.Contains(_collectDeviceSearchName)).ToList()">

                                 <ItemContent>
                                     @if (item.CurrentDevice != null)
                                    {

                                        <MListItem OnClick=@(()=>CollectDeviceInfo(item))>
                                            <MListItemContent>
                                                <MLabel Class=@((item.CurrentDevice?.DeviceStatus==DeviceStatusEnum.OnLine?"green--text":"red--text")+$" text-h6")>
                                                    <div class="mt-1  d-flex align-start justify-start" style="white-space: nowrap !important;overflow: hidden !important; text-overflow: ellipsis !important;" title=@item.CurrentDevice?.Name>
                                                        <span>@item.CurrentDevice?.Name</span>

                                                    </div>
                                                    <div style="white-space: nowrap !important;overflow: hidden !important; text-overflow: ellipsis !important;" class="text-caption">
                                                        @(item.CurrentDevice?.ActiveTime.ToDefaultDateTimeFormat(_initTimezone.TimezoneOffset) + "     " + typeof(DeviceStatusEnum).GetDescription(item.CurrentDevice?.DeviceStatus.ToString()))
                                                    </div>
                                                </MLabel>
                                            </MListItemContent>

                                        </MListItem>

                                        <MDivider></MDivider>

                                    }

                                </ItemContent>
                            </MVirtualScroll>


                        </MCard>

                    </MCol>
                    <MCol Md=7 Cols="12">
                        <MCard Style=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight + 80}px); overflow:auto)") Flat Elevation="0">
                             @if (_collectDriverItem != null && _collectDriverItem?.CurrentDevice != null)
                            {
                                var item = _collectDriverItem;
                                <MCard Style="height:100px;overflow:auto;" Flat Class="ml-4 my-4 ma-2" Elevation="0">

                                     <MCardActions>

                                         <MLabel Class=@((item.CurrentDevice?.DeviceStatus==DeviceStatusEnum.OnLine?"green--text":"red--text")+$" text-h6")>
                                             <div class="mt-1  d-flex align-center justify-space-between">
                                                 <span class="mx-3">@item.CurrentDevice?.Name</span>
                                                <span style="white-space: nowrap !important;overflow: hidden !important; text-overflow: ellipsis !important;" class="text-caption mx-3">@(item.CurrentDevice?.ActiveTime.ToDefaultDateTimeFormat(_initTimezone.TimezoneOffset) + "     " + typeof(DeviceStatusEnum).GetDescription(item.CurrentDevice?.DeviceStatus.ToString()))</span>
                                            </div>
                                        </MLabel>

                                        <MSpacer></MSpacer>
                                        @if (item?.DriverUIType != null)
                                        {
                                            <MTooltip Bottom Context="tip">
                                                 <ActivatorContent>
                                                     <MButton Disabled=@(!UserResoures.IsHasPageWithRole("/gatewayruntime/gatewaydevicerestart")) Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small Loading=_isRestart
                                                              OnClick=@(()=>GetCollectDriverUI())>
                                                         <MIcon>mdi-information-outline</MIcon>
                                                     </MButton>
                                                 </ActivatorContent>
                                                 <ChildContent>
                                                     <span>详细页面</span>
                                                 </ChildContent>
                                             </MTooltip>
                                        }

                                        @if (item?.CurrentDevice.IsRedundant==true)
                                        {
                                            <MTooltip Bottom Context="tip">
                                                 <ActivatorContent>
                                                     <MButton Disabled=@(!UserResoures.IsHasButtonWithRole("gatewaydevicerestart")) Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small OnClick=@(()=>DeviceRedundantThreadAsync(item.DeviceId))>
                                                         <MIcon>mdi-swap-horizontal</MIcon>
                                                     </MButton>
                                                 </ActivatorContent>
                                                 <ChildContent>
                                                     <span>切换冗余通道</span>
                                                 </ChildContent>
                                             </MTooltip>
                                        }


                                        <MTooltip Bottom Context="tip">
                                             <ActivatorContent>
                                                 <MButton Disabled=@(!UserResoures.IsHasPageWithRole("/gatewayruntime/devicevariable")) Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small Loading=_isRestart
                                                          OnClick=@(()=>NavigationManager.NavigateTo("/gatewayruntime/devicevariable?devicename="+item.CurrentDevice?.Name))>
                                                     <MIcon>mdi-information-outline</MIcon>
                                                 </MButton>
                                             </ActivatorContent>
                                             <ChildContent>
                                                 <span>相关变量</span>
                                             </ChildContent>
                                         </MTooltip>


                                         <MTooltip Bottom Context="tip">
                                             <ActivatorContent>
                                                 <MButton Disabled=@(!UserResoures.IsHasButtonWithRole("gatewaydevicepause")) Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small OnClick=@(()=>ConfigAsync(item.DeviceId,!item.CurrentDevice?.KeepRun))>
                                                     <MIcon>@(item.CurrentDevice?.KeepRun == true ? "mdi-pause" : "mdi-play")</MIcon>
                                                 </MButton>
                                             </ActivatorContent>
                                             <ChildContent>
                                                 <span>@(item.CurrentDevice?.KeepRun == true ? "暂停" : "运行")</span>
                                             </ChildContent>
                                         </MTooltip>

                                         <MTooltip Bottom Context="tip">
                                             <ActivatorContent>
                                                 <MButton Disabled=@(!UserResoures.IsHasButtonWithRole("gatewaydevicerestart")) Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small Loading=_isRestart OnClick=@(()=>RestartAsync(item.DeviceId))>
                                                     <MIcon>mdi-restart</MIcon>
                                                 </MButton>
                                             </ActivatorContent>
                                             <ChildContent>
                                                 <span>重启</span>
                                             </ChildContent>
                                         </MTooltip>

                                     </MCardActions>


                                 </MCard>

                                <MCard Style="height:200px;overflow:auto;" Flat Class="ml-4 my-4 ma-2" Elevation="0">
                                     <MDescriptions Class="ml-2" Dense Title="运行状态" Bordered=false>
                                         <MDescriptionsItem Span=3 Label=@item.CurrentDevice?.Description(a => a.ActiveTime)>@item.CurrentDevice?.ActiveTime.ToDefaultDateTimeFormat(_initTimezone.TimezoneOffset)</MDescriptionsItem>
                                            <MDescriptionsItem Label=@item.CurrentDevice?.Description(a => a.SourceVariableCount)>@item.CurrentDevice?.SourceVariableCount</MDescriptionsItem>
                                            <MDescriptionsItem Label=@item.CurrentDevice?.Description(a => a.DeviceVariableCount)>@item.CurrentDevice?.DeviceVariableCount</MDescriptionsItem>
                                            <MDescriptionsItem Label=@item.CurrentDevice?.Description(a => a.MethodVariableCount)>@item.CurrentDevice?.MethodVariableCount</MDescriptionsItem>
                                            <MDescriptionsItem Span=3 Class="red--text" Label=@item.CurrentDevice?.Description(a => a.LastErrorMessage)>@item.CurrentDevice?.LastErrorMessage</MDescriptionsItem>
                                        </MDescriptions>

                                        <MDescriptions Class="ml-2" Dense Title="配置信息" Bordered=false>
                                         <MDescriptionsItem Span=2 Label=@item.CurrentDevice?.Description(a => a.PluginName)>@item.CurrentDevice?.PluginName</MDescriptionsItem>
                                            <MDescriptionsItem Label=@item.CurrentDevice?.Description(a => a.IsLogOut)>@item.CurrentDevice?.IsLogOut</MDescriptionsItem>
                                            @foreach (var property in item.CurrentDevice?.DevicePropertys ?? new())
                                        {
                                            <MDescriptionsItem Span=@(property.PropertyName.Contains("BigText")?3:1) Label=@property.Description>@(property.PropertyName.Contains("Password") ? "******" : @property.Value)</MDescriptionsItem>
                                        }
                                    </MDescriptions>

                                </MCard>

                            }

                            <MCard Flat Class="ml-4">
                                 @if (_collectDriverItem != null && _collectDriverItem?.CurrentDevice != null)
                                {
                                    ICollection<(Microsoft.Extensions.Logging.LogLevel, string)> item = null;
                                    if (_collectDriverItem != null)
                                    {
                                        item = _collectDriverItem?.MessageItems;
                                    }
                                    if (item == null)
                                    {
                                        item = new List<(Microsoft.Extensions.Logging.LogLevel, string)>();
                                    }

                                    <ConsoleTxt Messages="item" Height=@($"calc(100vh - {BlazorResourceConst.DefaultHeight+480}px)")>

                                    </ConsoleTxt>



                                }
                            </MCard>

                        </MCard>
                    </MCol>
                </MRow>
            }
        </MTabItem>
        <MTabItem Value="2">
            @if (_tabNumber == 2)
            {
                <MRow>
@*                     <MCol Md=2 Cols="12">
                        <MCard Class="ma-2" Style=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight + 80}px); )")>
                            <MCardTitle>
                                <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="mx-2 my-1" @bind-Value="_uploadDeviceSearchName"
                                            Outlined Label=@typeof(Device).GetDescription(nameof(Device.DeviceGroup)) />
                             </MCardTitle>
                             <MTreeview Style=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight+240}px);overflow-y:auto") Dense TItem="string" TKey="string" ActiveChanged=@(async a=>
                                   {
                                   if(_uploadDeviceGroup!=a.FirstOrDefault())
                                   {
                                   _uploadDeviceGroup=a.FirstOrDefault(); 
                                   UploadDeviceQuery();
                                   }
                                   } )
                                        Items="_uploadDeviceGroups" ItemText="r=>r" ItemChildren="r=>null"
                                        Search="@_uploadDeviceSearchName"
                                      Activatable ItemKey=@(r=>r)>
                                 <LabelContent>
                                     <span title=@context.Item>
                                         @context.Item
                                    </span>
                                </LabelContent>
                            </MTreeview>
                        </MCard>
                    </MCol> *@
                    <MCol Md=5 Cols="12">
                        <MCard Height=@($"calc(100vh - {BlazorResourceConst.DefaultHeight+80}px)") Style="overflow-y:auto;" Flat Class="ml-2 my-4">
                             <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="mx-2 my-1" @bind-Value="_uploadDeviceSearchName"
                                            Outlined Label=@typeof(CollectDevice).GetDescription(nameof(CollectDevice.Name)) />

                             <MVirtualScroll Context="item" Height=@($"calc(100vh - {BlazorResourceConst.DefaultHeight+140}px)") OverscanCount=2 ItemSize="60" Items="_uploadDriverBases.WhereIF(!_uploadDeviceSearchName.IsNullOrEmpty(),a=>a.CurrentDevice.Name.Contains(_uploadDeviceSearchName)).ToList()">

                                 <ItemContent>
                                     @if (item.CurrentDevice != null)
                                    {

                                        <MListItem OnClick=@(()=>UploadDeviceInfo(item))>
                                            <MListItemContent>
                                                <MLabel Class=@((item.CurrentDevice?.DeviceStatus==DeviceStatusEnum.OnLine?"green--text":"red--text")+$" text-h6")>
                                                    <div class="mt-1  d-flex align-start justify-start" style="white-space: nowrap !important;overflow: hidden !important; text-overflow: ellipsis !important;" title=@item.CurrentDevice?.Name>
                                                        <span>@item.CurrentDevice?.Name</span>

                                                    </div>
                                                    <div style="white-space: nowrap !important;overflow: hidden !important; text-overflow: ellipsis !important;" class="text-caption">
                                                        @(item.CurrentDevice?.ActiveTime.ToDefaultDateTimeFormat(_initTimezone.TimezoneOffset) + "     " + typeof(DeviceStatusEnum).GetDescription(item.CurrentDevice?.DeviceStatus.ToString()))
                                                    </div>
                                                </MLabel>

                                            </MListItemContent>

                                        </MListItem>

                                        <MDivider></MDivider>

                                    }

                                </ItemContent>
                            </MVirtualScroll>


                        </MCard>

                    </MCol>
                    <MCol Md=7 Cols="12">
                        <MCard Style=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight + 80}px); overflow:auto)") Flat Elevation="0">
                             @if (_uploadDriverItem != null && _uploadDriverItem?.CurrentDevice != null)
                            {
                                var item = _uploadDriverItem;
                                <MCard Style="height:100px;overflow:auto;" Flat Class="ml-4 my-4 ma-2" Elevation="0">

                                     <MCardActions>


                                         <MLabel Class=@((item.CurrentDevice?.DeviceStatus==DeviceStatusEnum.OnLine?"green--text":"red--text")+$" text-h6")>
                                             <div class="mt-1  d-flex align-center justify-space-between">
                                                 <span class="mx-3">@item.CurrentDevice?.Name</span>
                                                <span style="white-space: nowrap !important;overflow: hidden !important; text-overflow: ellipsis !important;" class="text-caption mx-3">@(item.CurrentDevice?.ActiveTime.ToDefaultDateTimeFormat(_initTimezone.TimezoneOffset) + "     " + typeof(DeviceStatusEnum).GetDescription(item.CurrentDevice?.DeviceStatus.ToString()))</span>
                                            </div>
                                        </MLabel>

                                        <MSpacer></MSpacer>

                                        @if (item?.DriverUIType != null)
                                        {
                                            <MTooltip Bottom Context="tip">
                                                 <ActivatorContent>
                                                     <MButton Disabled=@(!UserResoures.IsHasPageWithRole("/gatewayruntime/gatewaydevicerestart")) Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small Loading=_isRestart
                                                              OnClick=@(()=>GetUploadDriverUI())>
                                                         <MIcon>mdi-information-outline</MIcon>
                                                     </MButton>
                                                 </ActivatorContent>
                                                 <ChildContent>
                                                     <span>详细页面</span>
                                                 </ChildContent>
                                             </MTooltip>
                                        }
                                        @if (item?.CurrentDevice.IsRedundant==true)
                                        {
                                            <MTooltip Bottom Context="tip">
                                                 <ActivatorContent>
                                                     <MButton Disabled=@(!UserResoures.IsHasButtonWithRole("gatewaydevicerestart")) Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small OnClick=@(()=>UpDeviceRedundantThreadAsync(item.DeviceId))>
                                                         <MIcon>mdi-swap-horizontal</MIcon>
                                                     </MButton>
                                                 </ActivatorContent>
                                                 <ChildContent>
                                                     <span>切换冗余通道</span>
                                                 </ChildContent>
                                             </MTooltip>
                                        }
                                        <MTooltip Bottom Context="tip">
                                             <ActivatorContent>
                                                 <MButton Disabled=@(!UserResoures.IsHasPageWithRole("/gatewayruntime/devicevariable")) Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small Loading=_isRestart
                                                          OnClick=@(()=>NavigationManager.NavigateTo("/gatewayruntime/devicevariable?uploaddevicename="+item.CurrentDevice?.Name))>
                                                     <MIcon>mdi-information-outline</MIcon>
                                                 </MButton>
                                             </ActivatorContent>
                                             <ChildContent>
                                                 <span>相关变量</span>
                                             </ChildContent>
                                         </MTooltip>


                                         <MTooltip Bottom Context="tip">
                                             <ActivatorContent>
                                                 <MButton Disabled=@(!UserResoures.IsHasButtonWithRole("gatewaydevicepause")) Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small OnClick=@(()=>UpConfigAsync(item.DeviceId,!item.CurrentDevice?.KeepRun))>
                                                     <MIcon>@(item.CurrentDevice?.KeepRun == true ? "mdi-pause" : "mdi-play")</MIcon>
                                                 </MButton>
                                             </ActivatorContent>
                                             <ChildContent>
                                                 <span>@(item.CurrentDevice?.KeepRun == true ? "暂停" : "运行")</span>
                                             </ChildContent>
                                         </MTooltip>




                                         <MTooltip Bottom Context="tip">
                                             <ActivatorContent>
                                                 <MButton Disabled=@(!UserResoures.IsHasButtonWithRole("gatewaydevicerestart")) Class="mx-2" @attributes="@tip.Attrs" Dark Fab Small Loading=_isRestart OnClick=@(()=> UpRestartAsync(item.DeviceId))>
                                                     <MIcon>mdi-restart</MIcon>
                                                 </MButton>
                                             </ActivatorContent>
                                             <ChildContent>
                                                 <span>重启</span>
                                             </ChildContent>
                                         </MTooltip>

                                     </MCardActions>




                                 </MCard>
                                <MCard Style="height:200px;overflow:auto;" Flat Class="ml-4 my-4 ma-2" Elevation="0">
                                     <MDescriptions Class="ml-2" Dense Title="运行状态" Bordered=false>
                                         <MDescriptionsItem Span=2 Label=@item.CurrentDevice?.Description(a => a.ActiveTime)>@item.CurrentDevice?.ActiveTime.ToDefaultDateTimeFormat(_initTimezone.TimezoneOffset)</MDescriptionsItem>
                                            <MDescriptionsItem Label=@item.CurrentDevice?.Description(a => a.DeviceVariableCount)>@item.CurrentDevice?.DeviceVariableCount</MDescriptionsItem>
                                            <MDescriptionsItem Span=3 Class="red--text" Label=@item.CurrentDevice?.Description(a => a.LastErrorMessage)>@item.CurrentDevice?.LastErrorMessage</MDescriptionsItem>
                                        </MDescriptions>

                                        <MDescriptions Class="ml-2" Dense Title="配置信息" Bordered=false>
                                         <MDescriptionsItem Span=2 Label=@item.CurrentDevice?.Description(a => a.PluginName)>@item.CurrentDevice?.PluginName</MDescriptionsItem>
                                            <MDescriptionsItem Label=@item.CurrentDevice?.Description(a => a.IsLogOut)>@item.CurrentDevice?.IsLogOut</MDescriptionsItem>
                                            @foreach (var property in item.CurrentDevice?.DevicePropertys ?? new())
                                        {
                                            <MDescriptionsItem Span=@(property.PropertyName.Contains("BigText")?3:1) Label=@property.Description>@(property.PropertyName.Contains("Password") ? "******" : @property.Value)</MDescriptionsItem>
                                        }
                                    </MDescriptions>

                                </MCard>
                            }

                            <MCard Flat Class="ml-4">
                                 @if (_uploadDriverItem != null && _uploadDriverItem?.CurrentDevice != null)
                                {
                                    ICollection<(Microsoft.Extensions.Logging.LogLevel, string)> item = null;
                                    if (_uploadDriverItem != null)
                                    {
                                        item = _uploadDriverItem?.MessageItems;
                                    }
                                    if (item == null)
                                    {
                                        item = new List<(Microsoft.Extensions.Logging.LogLevel, string)>();
                                    }

                                    <ConsoleTxt Messages="item" Height=@($"calc(100vh - {BlazorResourceConst.DefaultHeight+480}px)")>

                                    </ConsoleTxt>



                                }
                            </MCard>

                        </MCard>
                    </MCol>
                </MRow>
            }
        </MTabItem>

    </MTabsItems>




</MSheet>



<PDrawer @bind-Value="_isShowDetailUI" OnCancel="() => _isShowDetailUI = false"
         Title=@_importRef?.ToString() Persistent
          MaxWidth="1000">
     @if (_isShowDetailUI)
    {
        @if (_driverRender != null)
        {
            @*<MSheet Style=@($"height: calc(100vh - {BlazorResourceConst.DefaultHeight+50}px);border-radius:0px;")>*@
            @_driverRender
            @*</MSheet>*@
        }
    }

</PDrawer>

<style>
    .position-button {
        position: fixed !important;
        top: 10%;
        right: 10px;
        box-shadow: 1px 1px 8px;
        cursor: pointer;
    }

</style>









